package com.unibuy.smartdevice;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.os.Process;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.unibuy.smartdevice.database.SettingsDao;
import com.unibuy.smartdevice.databinding.ActivityMainBinding;
import com.unibuy.smartdevice.devices.DevNFCPay;
import com.unibuy.smartdevice.devices.DeviceType;
import com.unibuy.smartdevice.devices.Rs232Dev;
import com.unibuy.smartdevice.devices.UsbDev;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.exception.LogsUnsupportedOperationException;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.structure.SettingStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainSchedulerOnClick;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.ui.FontendActivity;
import com.unibuy.smartdevice.ui.ProductListActivity;
import com.unibuy.smartdevice.ui.SettingActivity;
import com.unibuy.smartdevice.ui.SettingTestActivity;
import com.unibuy.smartdevice.ui.SystemSetActivity;
import com.unibuy.smartdevice.ui.XyshjTestActivity;
import com.unibuy.smartdevice.ui.devs.flower.FlowerSlotListActivity;
import com.unibuy.smartdevice.utils.LanguageHelper;

import java.util.List;

public class MainActivity extends AppCompatActivityAbstract {
    @Override
    protected Context setCtx() {
        return this;
    }

    @Override
    protected Class<?> setCls() {
        return this.getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs());
    }

    private ActivityMainBinding binding;
    private HttpAPI httpAPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 讀取最後設定語言的設定
        LanguageHelper.applySavedLanguage(this);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        httpAPI = new HttpAPI(getHandlerMain());

        //---- 環境尺寸設定 ----
        ViewCompat.setOnApplyWindowInsetsListener(binding.main, (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //---- 環境尺寸設定 ----

        initialData();

        binding.buttonGotoSetting.setOnClickListener(v -> {
            if (!MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                if (MyApp.getInstance().getSuAccess().isEmpty()) {
                    showLoginDialog(getCtx());
                    return;
                }
            }

            getTools().gotoActivity(SettingActivity.class);
        });

        binding.buttonGotoSystemSet.setOnClickListener(v -> {
            if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                getHandlerMain().start("MainActivity", "＠先綁定機器");
                return;
            }

            if (MyApp.getInstance().getSuAccess().isEmpty()) {
                showLoginDialog(getCtx());
                return;
            }

            getTools().gotoActivity(SystemSetActivity.class);
        });

        binding.buttonGotoProductList.setOnClickListener(v -> {
            if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                getHandlerMain().start("MainActivity", "＠先綁定機器");
                return;
            }

            if (MyApp.getInstance().getSuAccess().isEmpty()) {
                showLoginDialog(getCtx());
                return;
            }

            getTools().gotoActivity(ProductListActivity.class);
        });

        binding.buttonGotoSlotList.setOnClickListener(v -> {
            if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                getHandlerMain().start("MainActivity", "＠先綁定機器");
                return;
            }

            if (MyApp.getInstance().getSuAccess().isEmpty()) {
                showLoginDialog(getCtx());
                return;
            }

            getTools().gotoActivity(FlowerSlotListActivity.class);
        });

        binding.buttonGotoShoppingPlatform.setOnClickListener(v -> {
            if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                getHandlerMain().start("MainActivity", "＠先綁定機器");
                return;
            }

            AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("隱藏導覽列測試")
                .setMessage("將導覽列隱藏並滑動看看，確定導覽列不會出現")
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MyApp.getInstance().setSuAccess("");
                        getTools().gotoActivity(FontendActivity.class);
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        getTools().hideSystemBars();
                    }
                })
                .create();
            dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
            dialog.show();
        });

        binding.buttonGotoSettingTest.setOnClickListener(v -> getTools().gotoActivity(SettingTestActivity.class));

        binding.buttonNfcCheckout.setOnClickListener(new ButtonNfcCheckoutOnClick(getHandlerMain()));

        binding.buttonNfcReset.setOnClickListener(new ButtonNfcResetOnClick(getHandlerMain()));

        binding.buttonQrCodeTest.setOnClickListener(new ButtonQrCodeTestOnClick(getHandlerMain()));

//        binding.buttonOtherTest.setOnClickListener(new ButtonOtherTextOnClick(getHandlerMain()));

        binding.buttonGotoXyshj.setOnClickListener(new ButtonGotoXyshjOnClick(getHandlerMain()));

        binding.buttonGotoXyshjTest.setOnClickListener(v -> {
            if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                getHandlerMain().start("MainActivity", "＠先綁定機器");
                return;
            }

            if (MyApp.getInstance().getSuAccess().isEmpty()) {
                showLoginDialog(getCtx());
                return;
            }

            getTools().gotoActivity(XyshjTestActivity.class);
        });

        binding.buttonLattice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLogs().info("開啟格子櫃格子");

            }
        });
    }

    private static class ButtonQrCodeTestOnClick extends HandlerMainSchedulerOnClick {
        public ButtonQrCodeTestOnClick(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            boolean openBarcode = true;
            try {
                UsbDev usbDev = new UsbDev(DeviceType.QRCODE_SCANNER);
                handlerMain.start(getClass().getSimpleName(), "@40秒內刷條碼");
                byte[] buffer = new byte[1000];
                usbDev.read(buffer, 100);
                for (int i=0; i<7; i++) {
                    if (isRun() && openBarcode) {
                        int size = usbDev.read(buffer, 5000);
                        if (size > 5) {
                            String barCodeString = new String(buffer, 0, size);
                            int sorLength = barCodeString.length();
                            barCodeString = barCodeString.trim();
                            int newLength = barCodeString.length();
                            getLogs().info(barCodeString +" 原碼長："+sorLength + " 新碼長:" + newLength);
                            handlerMain.start(getClass().getSimpleName(), getLogs().getMessage());
                            getLogs().clearMessage();
                            openBarcode = false;
                        }
                    }
                }
                usbDev.closePort();
            } catch (LogsUnsupportedOperationException | LogsIOException | LogsEmptyException e) {
//                getLogs().warning(e);
                getLogs().warning(e);
            }
        }

        @Override
        public void onClick(View v) {
            new ButtonQrCodeTestOnClick(getHandlerMain()).start();
        }

        @Override
        public boolean onLongClick(View v) {
            return false;
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    public static class ButtonNfcResetOnClick extends HandlerMainSchedulerOnClick {

        public ButtonNfcResetOnClick(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            try {
                Rs232Dev comPort2 = new Rs232Dev(MyApp.getInstance().getComPort2ByNFCPay());
                DevNFCPay devNFCPay = new DevNFCPay();
                comPort2.send(devNFCPay.reset());
                handlerMain.start(getClass().getSimpleName(), "刷卡機重啟啟動");
            } catch (LogsUnsupportedOperationException | LogsIOException e) {
//                getLogs().warning(e);
                getLogs().warning(e);
            }
        }

        @Override
        public void onClick(View v) {
            start();
        }

        @Override
        public boolean onLongClick(View v) {
            return false;
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    private class ButtonGotoXyshjOnClick extends HandlerMainSchedulerOnClick {

        public ButtonGotoXyshjOnClick(HandlerMain srcHandlerMain) {
            super(srcHandlerMain);
        }

        @Override
        public void onClick(View view) {
            start();
        }

        @Override
        public boolean onLongClick(View view) {
            return false;
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            List<PackageInfo> packages = MainActivity.this.getPackageManager().getInstalledPackages(0);
            for (PackageInfo packageInfo : packages) {
                if ("com.xyshj.machine".equals(packageInfo.packageName)) {
                    Intent it = new Intent("android.intent.action.xinyuan.setting");
                    it.putExtra("showLoginDialog", true);
                    MainActivity.this.startActivity(it);
                    android.os.Process.killProcess(Process.myPid());
                    return;
                }
            }
            handlerMain.start(getSrcHandlerMain().getLogs().getClassName(), "請先安裝興元管理程式");
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    public static class ButtonNfcCheckoutOnClick extends HandlerMainSchedulerOnClick {

        public ButtonNfcCheckoutOnClick(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }


        @Override
        protected void execute(HandlerMain handlerMain) {
            try {
                Rs232Dev comPort2 = new Rs232Dev(MyApp.getInstance().getComPort2ByNFCPay());
                DevNFCPay devNFCPay = new DevNFCPay();
                comPort2.send(devNFCPay.checkout());
                handlerMain.start(getClass().getSimpleName(), "刷卡機結帳啟動");
            } catch (LogsUnsupportedOperationException | LogsIOException e) {
//                getLogs().warning(e);
                getLogs().warning(e);
            }
        }
        @Override
        public void onClick(View v) {
            start();
        }

        @Override
        public boolean onLongClick(View v) {
            return false;
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.isLongPress()) {
                Toast.makeText(this, "返回主頁", Toast.LENGTH_SHORT).show();
                return true;
            }
        }

        return super.dispatchKeyEvent(event);
    }

    private void initialData() {
        if (MyApp.getInstance().getMachine() != null || MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
            SettingsDao settingsDao = new SettingsDao(this);
            SettingStructure setting = settingsDao.getOne(MyApp.getInstance().getMachine().getClass().getSimpleName());
            MyApp.getInstance().getMachine().setMachineID(setting.getData(1));
            settingsDao.close();
        }
    }

    public void showLoginDialog(Context context) {
        // 創建一個垂直的 LinearLayout
        LinearLayout layout = new LinearLayout(context);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(50, 20, 50, 10);

        // 帳號輸入框
        final EditText accessInput = new EditText(context);
        accessInput.setHint("帳號");
        layout.addView(accessInput);

        getTools().setImmHideByFocusChange(accessInput);
        getTools().setImmOpenByFocusChange(accessInput);

        // 密碼輸入框
        final EditText passwordInput = new EditText(context);
        passwordInput.setHint("密碼");
        passwordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        layout.addView(passwordInput);

        getTools().setImmHideByFocusChange(passwordInput);

        AlertDialog dialog = new AlertDialog.Builder(context)
                .setTitle("登入")
                .setView(layout)
                .setPositiveButton("登入", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String access = accessInput.getText().toString().trim();
                        String password = passwordInput.getText().toString().trim();

                        if (access.isEmpty() || password.isEmpty()) {
                            Toast.makeText(context, "請輸入帳號和密碼", Toast.LENGTH_SHORT).show();
                        } else {
                            try {
                                httpAPI.login(access, password);
                            } catch (LogsParseException e) {
                                throw new RuntimeException(e);
                            } catch (LogsSettingEmptyException e) {
                                throw new RuntimeException(e);
                            }
                        }

                        getTools().hideSystemBars();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getTools().hideSystemBars();
                        dialog.dismiss();
                    }
                }).create();
//        dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        dialog.show();
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
            binding.buttonGotoSystemSet.setVisibility(View.GONE);
            binding.buttonGotoProductList.setVisibility(View.GONE);
            binding.buttonGotoSlotList.setVisibility(View.GONE);
            binding.buttonGotoShoppingPlatform.setVisibility(View.GONE);
        } else {
            binding.buttonGotoSystemSet.setVisibility(View.VISIBLE);
            binding.buttonGotoProductList.setVisibility(View.VISIBLE);
            binding.buttonGotoSlotList.setVisibility(View.VISIBLE);
            binding.buttonGotoShoppingPlatform.setVisibility(View.VISIBLE);
        }
    }
}